<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">显示 ComponentA</button>
    <button @click="currentComponent = 'ComponentB'">显示 ComponentB</button>
    <button @click="currentComponent = 'ComponentC'">显示 ComponentC</button>

    <!-- 使用动态组件 -->
    <h2>使用动态组件</h2>
    <component :is="components[currentComponent]"></component>
    <!-- 使用keep-live 会缓存组件
    include - 字符串或正则表达式或数组。只有名称匹配的组件会被缓存。
    exclude - 字符串或正则表达式或数组。任何名称匹配的组件都不会被缓存。
    max - 数字。最多可以缓存多少组件实例
     -->
    <!-- API地址https://v2.cn.vuejs.org/v2/api/#keep-alive -->
    <h2>使用keep-live</h2>
    <!-- include ComponentB  ComponentC缓存-->
    <keep-alive :include="['ComponentB', 'ComponentC']">
      <component :is="components[currentComponent]"></component>
    </keep-alive>
    <!-- exclude -->
    <!-- 除了ComponentA，其他缓存 -->
    <!--     <keep-alive :exclude="['ComponentA']">
          <component :is="components[currentComponent]"></component>
    </keep-alive> -->
    <h2>使用异步组件</h2>
    <button @click="show = show == true ? false : true">显示异步组件</button>
    <ComponentD v-if="show" />
  </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
import ComponentC from './ComponentC.vue'
import { defineAsyncComponent } from 'vue'
const currentComponent = ref('ComponentA') // 默认显示 ComponentA
const show = ref(false)
defineOptions({
  name: 'asyncComponent'
})
const ComponentD = defineAsyncComponent(() => import('./ComponentD.vue'))
const components = computed(() => ({
  ComponentA,
  ComponentB,
  ComponentC
}))
</script>
